package com.spider.util;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spider.entity.JiliEntity;
import com.spider.entity.KubazhaEntity;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class KubazhaUtil {

    public static  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String encode(String keyword) {
        if(keyword==null||keyword.equals("")) return null;
        try {
            keyword = URLEncoder.encode(keyword, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return keyword;
    }

    /**
     * 拼接修改价格信息
     * @return
     */
    public static JSONObject getUpdatePriceBody(List<JiliEntity> list){
        JSONObject body=new JSONObject(new LinkedHashMap());
        if(CollectionUtil.isEmpty(list)){
            return null;
        }
        body.put("name","orig_price");
        //拼接params
        JSONObject params=new JSONObject(new LinkedHashMap());
        //拼接items
        JSONArray items=new JSONArray();
        for(JiliEntity entity:list){
            JSONObject entityJb=new JSONObject(new LinkedHashMap());
            BigDecimal base=entity.getPrice();
            BigDecimal discount=base;
            if(entity.getCxbs()!=null&&entity.getCxbs().equals("不打折")){
                entityJb.put("brand_name","希恩思");
            }else{
                //判断产品类型不是氘代的
                if(entity.getType()!=null&&entity.getType().equals("氘代")){
                    entityJb.put("brand_name","希恩思");
                }else{
                    entityJb.put("brand_name","希恩思");
                }
            }
            String gg=entity.getNum()+entity.getUnit();
            entityJb.put("package",gg);
            entityJb.put("catalog_no",entity.getHs());
            entityJb.put("orig_price",discount);
            items.add(entityJb);
        }
        params.put("items",items);
        body.put("params",params);
        return body;
    }

    /**
     * 拼接修改价格信息-新版svip
     * @return
     */
    public static JSONObject getUpdatePriceBodyNew(List<JiliEntity> list){
        JSONObject body=new JSONObject(new LinkedHashMap());
        if(CollectionUtil.isEmpty(list)){
            return null;
        }
        //拼接items
        JSONArray items=new JSONArray();
        for(JiliEntity entity:list){
            JSONObject entityJb=new JSONObject(new LinkedHashMap());
            BigDecimal base=entity.getPrice();
            BigDecimal discount=base;
            if(entity.getCxbs()!=null&&entity.getCxbs().equals("不打折")){
                body.put("brand_name","希恩思");
            }else{
                //判断产品类型不是氘代的
                if(entity.getType()!=null&&entity.getType().equals("氘代")){
                    body.put("brand_name","希恩思");
                }else{
                    body.put("brand_name","希恩思");
                }
            }
            String gg=entity.getNum()+entity.getUnit();
            entityJb.put("package",gg);
            entityJb.put("catalog_no",entity.getHs());
            entityJb.put("orig_price",discount);
            items.add(entityJb);
        }
        body.put("items",items);
        //body.put("params",params);
        return body;
    }

    /**
     * 拼接新增产品信息
     * 编辑也使用此产品信息
     * @return
     */
    public static MultiValueMap<String, String> insertProduceBody(List<KubazhaEntity> list, Map<String ,String> tokenMap){
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        if(CollectionUtil.isEmpty(list)){
            return null;
        }
        body.add("ucode",tokenMap.get("ucode"));
        body.add("token",tokenMap.get("token"));
        body.add("timestamp",tokenMap.get("timestamp"));
        //拼接reqcontent
        JSONArray reqcontent=new JSONArray();
        for(KubazhaEntity entity:list){
            JSONObject entityJb=new JSONObject(new LinkedHashMap());
/*            BigDecimal discountRate = new BigDecimal("0.65");
            BigDecimal discountedPrice =BigDecimal.ZERO;*/
            entityJb.put("品牌","First Standard");
            //entityJb.put("主图", BaseUrl.IMAGE_URL);
            entityJb.put("目录价(RMB)",entity.getPrice());
            //价格都用原价，通过商城后台折扣去控制
            entityJb.put("货号",entity.getHs());
//            String numStr =CommonUtil.formatFloat(entity.getNum());
//            String gg=numStr+entity.getUnit();
            entityJb.put("包装规格",entity.getGuige());
            entityJb.put("库存",entity.getKc());
            //todo
            entityJb.put("交货期",7);
            //1 生物试剂，无CAS
            //2 通用试剂，有CAS
            //化学试剂
            entityJb.put("产品分类","化学试剂");
            //以下为化学试剂单独需要添加的
            //添加逻辑cas如果是带逗号的则取第一个
            //Stirng cas = entity.getCas()
            entityJb.put("CAS",entity.getCas().contains(",")?entity.getCas().split(",")[0]:entity.getCas());
            //entityJb.put("质量等级","AR");
            entityJb.put("包装单位","瓶");

            entityJb.put("中文名称",entity.getName());
            //规则--纯度
            //entityJb.put("纯度",StringUtil.isNotEmpty(entity.getChundu())?entity.getChundu().substring(0, entity.getChundu().length()):null);
            entityJb.put("容量单位",entity.getJibenunit());
            entityJb.put("容量",formatNumber(entity.getJibenNum()));
            reqcontent.add(entityJb);
        }
        body.add("reqcontent",reqcontent.toString());
        return body;
    }


     public static String formatNumber(String num) {
        if (num != null && !num.isEmpty()) {
            try {
                // 解析字符串为浮点数
                double value = Double.parseDouble(num);
                // 格式化为两位小数的字符串
                return String.format("%.2f", value);
            } catch (NumberFormatException e) {
                // 如果解析失败，或者不是一个有效的数值，则返回原始字符串
                return num;
            }
        } else {
            // 如果为空，则返回原始字符串
            return num;
        }
    }

    /**
     * 拼接删除产品信息
     * @return
     */
    public static MultiValueMap<String, String> deleteProductBody(List<KubazhaEntity> list, Map<String ,String> tokenMap){
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        if(CollectionUtil.isEmpty(list)){
            return null;
        }
        body.add("ucode",tokenMap.get("ucode"));
        body.add("token",tokenMap.get("token"));
        body.add("timestamp",tokenMap.get("timestamp"));
        //拼接reqcontent
        JSONArray reqcontent=new JSONArray();
        for(KubazhaEntity entity:list){
            JSONObject entityJb=new JSONObject(new LinkedHashMap());
            entityJb.put("品牌","希恩思");
            entityJb.put("货号",entity.getHs());
            String numStr =CommonUtil.formatFloat(entity.getNum());
            String gg=numStr+entity.getUnit();
            entityJb.put("包装规格",gg);
            reqcontent.add(entityJb);
        }
        body.add("reqcontent",reqcontent.toString());
        return body;
    }

    /**
     * 拼接查询结构信息
     * @return
     */
    public static MultiValueMap<String, Object> getResultBody(Map<String ,String> tokenMap,String date){
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("ucode",tokenMap.get("ucode"));
        body.add("token",tokenMap.get("token"));
        body.add("timestamp",tokenMap.get("timestamp"));
        SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtil.isNotEmpty(date)){
            body.add("date",date);
        }else{
            body.add("date",format.format(new Date()));
        }
        //body.add("date","2023-12-24");
        body.add("page",1);
        return body;
    }

    /**
     * 推送特殊价格
     * @return
     */
    public static MultiValueMap<String, String> addBatchProductBody(List<KubazhaEntity> list, Map<String ,String> tokenMap){
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        if(CollectionUtil.isEmpty(list)){
            return null;
        }
        body.add("ucode",tokenMap.get("ucode"));
        body.add("token",tokenMap.get("token"));
        body.add("timestamp",tokenMap.get("timestamp"));
        //拼接reqcontent
        JSONArray reqcontent=new JSONArray();
        int num =0;
        for(KubazhaEntity entity:list){
            if(entity.getPrice().compareTo(entity.getOldPrice())==0){
                continue;
            }
            num++;
            JSONObject entityJb=new JSONObject(new LinkedHashMap());
            entityJb.put("品牌","希恩思");
            entityJb.put("单价",entity.getPrice());
            entityJb.put("货号",entity.getHs());
            String numStr =CommonUtil.formatFloat(entity.getNum());
            String gg=numStr+entity.getUnit();
            entityJb.put("包装规格",gg);
            try{
                int intValue = CommonUtil.getStock(entity.getStock(),entity.getKc(),entity.getJibenNum());
                entityJb.put("库存",intValue);
            }catch (Exception e){
                entityJb.put("库存",0);
            }
            entityJb.put("平台编号","全部");
            reqcontent.add(entityJb);
        }
        body.add("reqcontent",reqcontent.toString());
        System.out.println("库巴扎设置特殊价格数量为："+num);
        return body;
    }

    /**
     * 推送特殊价格
     * @return
     */
    public static String getFailResult(Map<String ,String> tokenMap,String date,int page,String url){
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
        paramMap.add("ucode",tokenMap.get("ucode"));
        paramMap.add("token",tokenMap.get("token"));
        paramMap.add("timestamp",tokenMap.get("timestamp"));
        paramMap.add("date",date);
        paramMap.add("page",page);
        // Set up headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // Create the request entity
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(paramMap, headers);

        // Make the POST request
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> result = restTemplate.postForEntity(url, requestEntity, String.class);

        System.out.println("返回结果：" + result.getBody());
        return result.getBody();
    }



    public static void convertPrice(List<KubazhaEntity> list){
        for(KubazhaEntity entity:list) {
            BigDecimal base = entity.getPrice();
            BigDecimal discount = base;
            entity.setOldPrice(base);
            BigDecimal discountRate = new BigDecimal("0.65");
            BigDecimal discountedPrice = BigDecimal.ZERO;
            try {
                if (StringUtil.isEmpty(entity.getCxbs())) {
                    // 计算折扣后的价格：base * discountRate
                    discountedPrice = base.multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
                } else {
                    if (entity.getCxbs().equals("不打折")) {
                        discountedPrice = discount;
                    } else {
                        //判断是否是氘代
                        //判断产品类型不是氘代的
                        if (StringUtil.isNotEmpty(entity.getType()) && entity.getType().equals("氘代")) {
                            discountedPrice = discount;
                        } else {
                            discountedPrice = base.multiply(discountRate).setScale(2, RoundingMode.HALF_UP);
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println("价格报错：" + entity.getHuohao());
            }
            entity.setPrice(discountedPrice);
        }
    }
}
